//
//  NSMutableArray+WeakReference.m
//  MFWSdk
//
//  Created by Song Xiaofeng on 13-7-24.
//  Copyright (c) 2013年 Mafengwo Inc. All rights reserved.
//

#import "NSMutableArray+WeakReference.h"
#import "WeakReference.h"
#import "LoadableCategory.h"

MAKE_CATEGORIES_LOADABLE(MFWSdk_NSMutalbelArray_WeakReference)

@implementation NSMutableArray (WeakReference)


- (void)addWeakObject:(id)anObject;
{
    [self addObject:[WeakReference weakReferenceWithObject:anObject]];
}

- (void)insertWeakObject:(id)anObject atIndex:(NSUInteger)index;
{
    [self insertWeakObject:[WeakReference weakReferenceWithObject:anObject] atIndex:index];
}

- (void)replaceWeakObjectAtIndex:(NSUInteger)index withWeakObject:(id)anObject;
{
    [self replaceWeakObjectAtIndex:index withWeakObject:[WeakReference weakReferenceWithObject:anObject]];
}


- (id)lastWeakObject;
{
    WeakReference *weakRef = [self lastObject];
    if ([weakRef isKindOfClass:[WeakReference class]])
    {
        return [weakRef nonretainedObjectValue];
    }
    return nil;
}

- (id)weakObjectAtIndex:(NSUInteger)index;
{
    WeakReference *weakRef = [self objectAtIndex:index];
    if ([weakRef isKindOfClass:[WeakReference class]])
    {
        return [weakRef nonretainedObjectValue];
    }
    return nil;
}

- (BOOL)containsWeakObject:(id)anObject;
{
    id ddd = [WeakReference weakReferenceWithObject:anObject];
    BOOL exsit = [self containsObject:ddd];
    return exsit;
}

- (void)removeWeakObject:(id)anObject;
{
    NSMutableArray *tobeRemoved = [NSMutableArray array];
    
    int count = [self count];
    for (int i = 0; i < count; i++)
    {
        WeakReference *weakRef = [self objectAtIndex:i];
        if (!weakRef.nonretainedObjectValue || [weakRef nonretainedObjectValue] == anObject)
        {
            [tobeRemoved addObject:weakRef];
        }
    }
    [self removeObjectsInArray:tobeRemoved];
}

- (NSUInteger)aliveCount;
{
    NSUInteger count = [self count];
    if (count > 0)
    {
        __block NSUInteger alive = 0;
        for (int i = 0; i < count; i++)
        {
            id obj = [self objectAtIndex:i];
            if ([obj isKindOfClass:[WeakReference class]])
            {
                if ([(WeakReference*)obj nonretainedObjectValue] == nil)
                {
                    continue;
                }
            }
            alive ++;
        }
        
        return alive;
    }
    return count;
}
@end
